package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.entity.Message;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject: community
 * @BelongsPackage: com.nowcoder.community.controller.interceptor
 * @Author: Master_XXJS
 * @CreateTime: 2023-01-08  00:09
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class MessageInterceotor implements HandlerInterceptor {
    @Autowired
    private MessageService messageService;
    @Autowired
    private HostHolder hostHolder;

    //post handle 表示是在controller 执行完之后进行拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null){
            //null 是查全部
            int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);
            int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
            //返回controller执行完之后的页面
            modelAndView.addObject("allUnreadCount",noticeUnreadCount+letterUnreadCount);
        }

    }
}

